﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Drawing;

namespace Taurus.Platform.BLL
{
    /// <summary>
    /// 图片管理类
    /// </summary>
    public class ImageManager
    {
        string _dirPath;

        public ImageManager(string dir)
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            _dirPath = dir;
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name">图片保存名称</param>
        /// <param name="isCompulsory">是否强制更新</param>
        public Image DownImage(string url, string name, bool isCompulsory)
        {
            Uri uri = new Uri(url);
            if (name == string.Empty)
            {
                name = uri.Segments[uri.Segments.Length - 1];
            }
            if (!File.Exists(_dirPath + name) || isCompulsory)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Image a = Image.FromStream(response.GetResponseStream());
                a.Save(_dirPath + name);
                return a;
            }
            else
            {
                return GetImage(name);
            }

        }
        public Image DownImage(string url)
        {
           return DownImage(url,string.Empty, false);
        }
        public Image DownImage(string url, string name)
        {
            return DownImage(url, name, false);
        }
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="name">图片名</param>
        /// <returns></returns>
        public Image GetImage(string name)
        {
            if (!File.Exists(_dirPath + name))
            {
                return null;
            }
            return Image.FromFile(_dirPath + name);
        }
    }
}
